package com.example.tool.util.yunda;

import com.alibaba.fastjson.JSONObject;
import com.yundasys.OpenApiHttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.UUID;
@Component
public class YunDaApiUtil {
    private static RetryTemplate retryTemplate;
    private static final String SUBSCRIBE_API_URL = "https://openapi.yundaex.com/openapi/outer/logictis/subscribe";
    private static final String LOGICTIS_QUERY_API_URL = "https://openapi.yundaex.com/openapi/outer/logictis/query";
    private static final String APP_KEY = "003961";
    private static final String APP_SECRET = "d8db4f1777bf425799119fa759616c6c";
    // 请求记录队列，保存最近请求的时间戳
    private static final Queue<Long> requestTimestamps = new LinkedList<>();
    // 限制参数：2秒内最多5次请求
    private static final int TIME_WINDOW_SECONDS = 1;
    private static final int MAX_REQUESTS = 1;
    // 超过限制后的休眠时间
    private static final long SLEEP_TIME_MS = 5000;
    @Autowired
    public void setRetryTemplate(RetryTemplate retryTemplate) {
        YunDaApiUtil.retryTemplate = retryTemplate;
    }
    public static RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
    /**
     * 查询物流信息（带速率限制）
     * @param waybillNo 运单号
     * @return 物流信息JSON对象
     * @throws InterruptedException 如果线程被中断
     * @throws RuntimeException 如果查询失败
     */
    public static JSONObject queryLogistics(String waybillNo) {
//        return retryTemplate.execute(context -> {
//        synchronized (requestTimestamps) {
//        // 移除2秒前的请求记录
//        long currentTime = System.currentTimeMillis();
//        long windowStart = currentTime - TIME_WINDOW_SECONDS * 1000;
//
//        while (!requestTimestamps.isEmpty() && requestTimestamps.peek() < windowStart) {
//        requestTimestamps.poll();
//        }
//
//        // 检查当前请求数是否超过限制
//        if (requestTimestamps.size() >= MAX_REQUESTS) {
//        try {
//            System.out.println("请求过于频繁，休眠" + SLEEP_TIME_MS + "毫秒");
//            Thread.sleep(SLEEP_TIME_MS);
//            // 休眠后清空记录，重新开始计数
//            requestTimestamps.clear();
//        } catch (InterruptedException e) {
//            Thread.currentThread().interrupt();
//            throw new RuntimeException("请求被中断", e);
//        }
//        }
//
//        // 记录当前请求时间
//        requestTimestamps.offer(currentTime);
//        }

        return doQueryLogistics(waybillNo);
//        });
    }


    /**
     * 查物流
     * @param waybillNo
     * @return
     */
    public static JSONObject  doQueryLogistics(String waybillNo){
//        JSONObject subscribeParam = new JSONObject();
//        List<Order> orders = new ArrayList<>();
//        Order order = new Order();
//        order.setMailno(waybillNo);
//        order.setOrderid(UUID.randomUUID().toString().replace("-",""));
//        orders.add(order);
//        subscribeParam.put("orders",orders);
//        String s = OpenApiHttpUtils.doPostJson(SUBSCRIBE_API_URL, subscribeParam.toJSONString(), APP_KEY, APP_SECRET);
        trackSubSubscribe(waybillNo);
        JSONObject logictisQueryParam=new JSONObject();
        logictisQueryParam.put("mailno",waybillNo);
        String result = OpenApiHttpUtils.doPostJson(LOGICTIS_QUERY_API_URL, logictisQueryParam.toJSONString(), APP_KEY, APP_SECRET);
        return JSONObject.parseObject(result);
    }

    /**
     * 查物流
     * @param waybillNo
     * @return
     */
    public static void  trackSubSubscribe(String waybillNo){
        JSONObject subscribeParam = new JSONObject();
        List<Order> orders = new ArrayList<>();
        Order order = new Order();
        order.setMailno(waybillNo);
        order.setOrderid(UUID.randomUUID().toString().replace("-",""));
        orders.add(order);
        subscribeParam.put("orders",orders);
        String s = OpenApiHttpUtils.doPostJson(SUBSCRIBE_API_URL, subscribeParam.toJSONString(), APP_KEY, APP_SECRET);
        System.out.println(s);
    }

    public static void main(String[] args) {
      trackSubSubscribe("434661801708305");
    }
}